package com.example.demo.filter;

import com.example.demo.beans.Result;
import com.example.demo.service.EmpService;
import com.example.demo.util.CommUtil;
import com.example.demo.util.Constant;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName="demoFilter",urlPatterns="/*")
@Log4j2
public class DemoFilter implements Filter {
    @Value("${Origin.url}")
    private String originUrl;

    @Value("${ignoreUrl}")
    private String ignoreUrl;

    @Autowired
    EmpService empService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        //解决跨域调用的问题
        response.addHeader("Access-Control-Allow-Origin", originUrl);

        log.info("请求URL：{}",request.getRequestURI());

        if(!CommUtil.checkIgnoreUrl(request,ignoreUrl)){
            Result result = empService.checkLogin(request);
            if(!result.isSuccess()){
                log.info("登录超时！");
                CommUtil.responseData(response,result);
                return;
            }

        }

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
